﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace AllTalk
{
    public partial class LoginPage : PhoneApplicationPage
    {
        private bool _dataBound;

        public LoginPage()
        {
            InitializeComponent();
        }

        private void SignInButton_Click(object sender, RoutedEventArgs e)
        {
            App.LoginViewModel.SaveData();
            SignIn();
        }

        private void SignIn()
        {   
            if (!App.ConnectionManager.IsConnected)
            {
                this.SignInButton.IsEnabled = false;
                App.LoginViewModel.Status = "Signing in...";
                App.ConnectionManager.Connect(App.LoginViewModel.Email, App.LoginViewModel.Password);
                App.ConnectionManager.ConnectionCompleted += new EventHandler<ConnectionEventArgs>(ConnectionManager_ConnectionComleted);
            }
            else
            {
                NavigationService.Navigate(UriConstants.MainPage);
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (!_dataBound)
            {
                if (!App.LoginViewModel.IsLoaded)
                {
                    App.LoginViewModel.LoadData();
                }
                this.DataContext = App.LoginViewModel;
                _dataBound = true;
                if (App.LoginViewModel.CanAutoSignIn)
                {
                    this.SignIn();
                }
            }
        }

        private void ConnectionManager_ConnectionComleted(object sender, ConnectionEventArgs e)
        {
            App.ConnectionManager.ConnectionCompleted -= new EventHandler<ConnectionEventArgs>(ConnectionManager_ConnectionComleted);
            if (e.Error != null)
            {
                App.LoginViewModel.Status = String.Format("Error: {0}", e.Error.Message);
            }
            else
            {
                App.LoginViewModel.Status = String.Empty;
                NavigationService.Navigate(UriConstants.MainPage);
            }
            this.SignInButton.IsEnabled = true;
        }
    }

}